package gitee.derumin.teleport_compass.commands;

import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import gitee.derumin.lib_for_derumin.api.features.ChunkDataTools;
import gitee.derumin.lib_for_derumin.logger.DeruminLogger;
import gitee.derumin.teleport_compass.waypoints.Waypoints;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.command.argument.ArgumentTypes;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;


import static net.minecraft.server.command.CommandManager.*;

public class ProtectWaypointCommand {
    public static void init(){
        CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
            dispatcher.register(literal("protectWaypoint")
                    .requires(source -> source.hasPermissionLevel(2))
                    .then(argument("pos", BlockPosArgumentType.blockPos())
                            .executes(context -> executeProtect(context, true))
                            .then(argument("protect?", BoolArgumentType.bool())
                                    .executes(context -> executeProtect(context, BoolArgumentType.getBool(context, "protect?"))))));
        });
    }

    private static int executeProtect(CommandContext<ServerCommandSource> context, boolean bl){
        BlockPos blockPos = BlockPosArgumentType.getBlockPos(context, "pos");
        ServerWorld world = context.getSource().getWorld();
        Waypoints waypoints = (Waypoints) ChunkDataTools.getExtraData(world, blockPos, Waypoints.ID);
        if (waypoints != null && waypoints.hasWaypoint(blockPos)){
            int i = ChunkDataTools.setBlockStableRule(world, blockPos, bl);
            if (i == 1){
                DeruminLogger.getLogger().info("路标'" + waypoints.getWaypointName(blockPos) + "'被设定为" + (bl? "受保护的" : "不受保护的"), DeruminLogger.AnnounceType.ALL);
                return 1;
            }
            return 0;
        }
        return -1;
    }
}
